<?php

namespace app\api\controller;

use app\api\library\Code;
use app\api\model\Banner;
use app\api\model\Goods;
use app\api\model\ShopBrand;
use app\api\model\ShopCategory;
use app\api\validate\IndexValidate;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\library\Tools;
use EasyWeChat\Factory;
use think\Db;
use think\Model;
use think\Request;

/**
 * B-首页接口
 * @ApiWeigh    (99)
 */
class Index extends Api {
	protected $noNeedLogin = ['jssdk'];
	protected $noNeedRight = ['*'];

	protected $validate = null;
	protected $goodsModel = null;

	public function __construct( Request $request = null ) {
		parent::__construct( $request );

		$this->validate   = new IndexValidate();
		$this->goodsModel = new Goods();
	}

	/**
	 * @ApiTitle    (首页数据)
	 * @ApiSummary  (首页数据)
	 * @ApiMethod (POST)
	 *
	 * @ApiParams   (name="category_id", type="integer", required=true, description="商品类型:0=默认全部传0,1=画作,2=指挥手办,3=摄影技术,4=最新作品")
	 * @ApiParams   (name="keyword", type="string", required=false, description="商品名称关键词")
	 *
	 * @ApiReturnParams   (name="banner", type="array", description="轮播图")
	 * @ApiReturnParams   (name="type", type="integer", description="类型:0=不跳转,1=跳转")
	 * @ApiReturnParams   (name="image", type="string", description="轮播图物理路径")
	 * @ApiReturnParams   (name="object_id", type="integer", description="type为1时:跳转商品详情id")
	 *
	 * @ApiReturnParams   (name="brand", type="array", description="首页金刚区logo&其标题")
	 * @ApiReturnParams   (name="name", type="string", description="标题")
	 * @ApiReturnParams   (name="image", type="string", description="logo物理路径")
	 *
	 * @ApiReturnParams   (name="goods", type="object", description="商品对象")
	 * @ApiReturnParams   (name="total", type="object", description="商品总数")
	 * @ApiReturnParams   (name="per_page", type="object", description="每页数据")
	 * @ApiReturnParams   (name="current_page", type="object", description="当前页")
	 * @ApiReturnParams   (name="last_page", type="object", description="最后一页")
	 * @ApiReturnParams   (name="data", type="array", description="商品数组")
	 * @ApiReturnParams   (name="id", type="integer", description="商品ID")
	 * @ApiReturnParams   (name="name", type="string", description="商品名称")
	 * @ApiReturnParams   (name="category_id", type="integer", description="1=画作,2=指挥手办,3=摄影技术,4=最新作品")
	 * @ApiReturnParams   (name="image", type="string", description="商品头图物理路径")
	 * @ApiReturnParams   (name="goods_price", type="float", description="商品价格")
	 *
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 */
	public function index() {
		if ( !( $this->validate->scene( 'index' )->check( $this->param ) ) ) {
			$this->error( $this->validate->getError() );
		}

		$keyword  = isset( $this->param['keyword'] ) ? $this->param['keyword'] : '';
		$brand_id = isset( $this->param['category_id'] ) ? $this->param['category_id'] : 0;

		$banner            = new Banner();
		$ShopCategoryModel = new ShopCategory();

		//轮播图
		$data['banner'] = $banner->limit( 5 )->order( 'weigh', 'desc' )->select();
		//首页金刚区
		$data['brand'] = $ShopCategoryModel->order( 'id', 'asc' )->select();
		//商品列表
		$field = 'id,name,category_id,image,goods_price';

		$data['goods'] = $this->goodsModel->field( $field )
			->where( function ( $query ) use ( $brand_id ) {
				if ( $brand_id !== 0 ) {
					switch ( $brand_id ) {
						case 1:
							$query->where( 'category_id', 1 );
							break;
						case 2:
							$query->where( 'category_id', 2 );
							break;
						case 3:
							$query->where( 'category_id', 3 );
							break;
						case 4:
							$query->where( 'category_id', 4 );
							break;
						default:
							break;
					}
				}
			} )
			->where( function ( $query ) use ( $keyword ) {
				if ( !empty( $keyword ) ) {
					$query->whereLike( 'name', '%' . $keyword . "%" );
				}
			} )
			->order('createtime desc')
			->paginate( 10 );
		$this->success( '首页数据显示', $data );
	}

	/**
	 * @ApiTitle    (商品详情)
	 * @ApiSummary  (点击商品列表中的商品查看商品的详细信息)
	 * @ApiMethod (POST)
	 *
	 * @ApiParams   (name="goods_id", type="integer", required=true, description="商品id")
	 *
	 * @ApiReturnParams   (name="id", type="integer", description="商品id")
	 * @ApiReturnParams   (name="name", type="string", description="商品名称")
	 * @ApiReturnParams   (name="goods_no", type="string", description="商品编号")
	 * @ApiReturnParams   (name="category_id", type="integer", description="商品类别")
	 * @ApiReturnParams   (name="images", type="array", description="商品图组")
	 * @ApiReturnParams   (name="content", type="string", description="商品详情介绍富文本")
	 * @ApiReturnParams   (name="goods_price", type="string", description="商品价格")
	 * @ApiReturnParams   (name="stock_num", type="string", description="商品库存")
	 * @ApiReturnParams   (name="createtime", type="string", description="上架时间")
	 *
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 */

	public function goods_details() {
		if ( !( $this->validate->scene( 'details' )->check( $this->param ) ) ) {
			$this->error( $this->validate->getError() );
		}

		$goods_id = $this->param['goods_id'];

		$field = 'id,name,goods_no,category_id,images,content,goods_price,stock_num,createtime';
		$info  = $this->goodsModel->field( $field )->where( 'id', $goods_id )->where( 'status', 1 )->find();
		$info['content'] = Tools::set_img_style($info['content']);
		//处理时间戳
		$info['createtime'] = date( 'Y-m-d H:i', $info['createtime'] );
		$this->success( '商品详情信息', $info );
	}

    /**
     * @ApiTitle    (jssdk)
     * @ApiMethod   (POST)
     * @ApiParams   (name=url, type=string, required=false, description="当前url")
     * @ApiReturn   ({
        "code": 1,
        "msg": "sdk",
        "time": "1644628208",
        "data": {
            "debug": false, //是否开启调试
            "beta": false,
            "jsApiList": [ //jsApiList
                "checkJsApi",
                "chooseWXPay",
                "chooseImage",
                "previewImage",
                "uploadImage",
                "downloadImage",
                "updateAppMessageShareData",
                "updateTimelineShareData",
                "onMenuShareTimeline",
                "onMenuShareAppMessage",
            ],
            "appId": "", //appId
            "nonceStr": "XClQcJvAGn", //随机字符串
            "timestamp": 1644628208, //时间戳
            "url": "", //当前url
            "signature": "" //签名
        }
    })
     */
    public function jssdk()
    {
        $params = $this->request->post();
        $apis = [
            'checkJsApi',
            'chooseWXPay', //微信支付
            'chooseImage', //拍照或从手机相册中选图接口
            'previewImage', //预览图片接口
            'uploadImage', //上传图片
            'downloadImage', // 下载图片接口
            'updateAppMessageShareData', // 自定义“分享给朋友”及“分享到QQ”按钮的分享内容
            'updateTimelineShareData', // 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容
            'onMenuShareTimeline', // 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口（即将废弃）
            'onMenuShareAppMessage', // 获取“分享给朋友”按钮点击状态及自定义分享内容接口（即将废弃）
        ];
        $url = urldecode($params['url']);

        $config = get_addon_config('third')['wechat'];
        $config['secret'] = $config['app_secret'];
        $app = Factory::officialAccount($config);
        $res = $app->jssdk->setUrl($url)->buildConfig($apis, $debug = false, $beta = false, $json = false);
        $this->success('sdk', $res);
    }
}
